#include "database.h"

Database::Database(vector<string> l) {
    conn = new mysqlpp::Connection(false);

    for(size_t i = 0; i < l.size(); i++) {
	if(l[i] == "--server")
	    m_address = l[i+1];
	else if(l[i] == "--user")
	    m_user = l[i+1];
	else if(l[i] == "--password")
	    m_passwd = l[i+1];
	else if(l[i] == "--database")
	    m_database = l[i+1];
	else if(l[i] == "--create-tables")
	    if(m_address.empty() || m_user.empty() ||
	       m_passwd.empty() || m_database.empty()) {
		getMySQLConnectionData();
		createTables();
	    } else {
		createTables();
	    }
    }


	getMySQLConnectionData();
}

Database::~Database() {
    delete conn;
}

void Database::createTables() {
    cout << "Creating tables" << endl;
    if(connectToMySQL()) {
	mysqlpp::Query query(conn);
	query <<
	    "CREATE TABLE urt_games (" <<
	    "id INT NOT NULL AUTO_INCREMENT ," <<
	    "map VARCHAR( 255 ) NOT NULL ," <<
	    "mode INT NOT NULL ," <<
	    " PRIMARY KEY ( id ) " <<
	    ") ENGINE = InnoDB";
	
	query.reset();
    }
}

void Database::getMySQLConnectionData() {
    while(m_address.empty() || m_user.empty() || 
	  m_passwd.empty() || m_database.empty()) {
	if(m_address.empty()) {
	    cout << "Server's address :";
	    cin >> m_address;
	}
	else if(m_user.empty()) {
	    cout << "User :";
	    cin >> m_user;
	}
	else if(m_passwd.empty()) {
	    cout << "Password :";
	    cin >> m_passwd;
	}
	else if(m_database.empty()) {
	    cout << "Database :";
	    cin >> m_database;
	}
    }
}

bool Database::connectToMySQL() {
    if(conn->connect(m_database.c_str(), m_address.c_str(),
		     m_user.c_str(), m_passwd.c_str()))
       return true;
    else {
	cerr << "Database connection failed:" << conn->error() << endl;
	return false;
    }
}

void Database::newGameQuery(const string map, const string gameType) {
    if(connectToMySQL()) {
	mysqlpp::Query query(conn);
	query << "INSERT INTO %6:table VALUES " << "('', %0q, %1)";
	query.parse();
	query.template_defaults["table"] = "urt_games";
	query.execute(map, gameType);
	query.reset();
    }
}

